layui.config({
    base: "../../js/"
}).extend({
    "jqCommon": "jqCommon"
})
/*全局搜索参数*/
var type;
var vipType;
var vipStartTime;
var vipEndTime;
var param;

layui.use(['form', 'layer', 'table', 'laytpl', 'jqCommon', 'util', 'laydate'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        jqcommon = layui.jqCommon,
        util = layui.util,
        laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
        elem: '#vipStartTime' //指定元素
        ,type: 'datetime'
    });

    laydate.render({
        elem: '#vipEndTime' //指定元素
        ,type: 'datetime'
    });

    //用户列表
    var tableIns = table.render({
        elem: '#userList',
        url: 'http://mini.yantaibaixing.cn/users',
        // where: {token: 'sasasas', id: 123}, //如果无需传递额外参数，可不加该参数
        method: 'get', //如果无需自定义HTTP类型，可不加该参数
        //request: {} //如果无需自定义请求参数，可不加该参数
        response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            , statusCode: 200 //成功的状态码，默认：0
            , msgName: 'message' //状态信息的字段名称，默认：msg
            , countName: 'total' //数据总数的字段名称，默认：count
            , dataName: 'datas' //数据列表的字段名称，默认：data
        },
        done: function (res, curr, count) {
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            // console.log(res);

            //得到当前页码
            // console.log(curr);

            //得到数据总量
            // console.log(count);
        },
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 20,
        id: "userListTable",
        cols: [[
            {title: '操作', templet: '#userListBar',width: 300, align: "left"},
            {field: 'name', title: '姓名', width: 130, align: "center"},
            {field: 'phone', title: '手机号', width: 130, align: "center"},
            {
                field: 'gender', title: '性别', width: 60, align: 'center', templet: function (d) {
                return d.gender == 1 ? "男" : "女";
            }
            },
            {
                field: 'type', title: '类型', width: 70, align: 'center', templet: function (d) {
                return d.type == 1 ? "个人" : "商户";
            }
            },
            {
                field: 'vipNo', title: '会员号', width: 130, align: 'center', templet: function (d) {
                if (d.vipNo == '无') {
                    return '无';
                } else {
                    return d.vipNoPrefix + d.vipNo;
                }
            }
            },
            {
                field: 'vipType', title: '会员类型', width: 100, align: 'center', templet: function (d) {
                if (d.vipType == 1) {
                    return "非会员";
                } else if (d.vipType == 2) {
                    return "商户会员";
                } else if (d.vipType == 3) {
                    return "付费会员";
                } else if (d.vipType == 4) {
                    return "赠送会员";
                } else if (d.vipType == 5) {
                    return "试用会员";
                }
            }
            },
            {field: 'pName', title: '邀请人姓名', width: 130, align: "center"},
            {field: 'pPhone', title: '邀请人手机号', width: 130, align: "center"},
            {field: 'shopName', title: '商户名称', width: 300, align: "center"},
            {
                field: 'discount', title: '折扣', width: 70, align: 'center', templet: function (d) {
                if (d.discount == '无') {
                    return '无';
                } else {
                    return d.discount + "折";
                }
            }
            },
            {field: 'shopAdress', title: '商户地址', width: 300, align: "center"},
            {
                field: 'bankName', title: '银行名称', width: 200, align: 'center', templet: function (d) {
                if (d.bankName == '无') {
                    return '无';
                } else {
                    return d.bankName;
                }
            }
            },
            {
                field: 'bankCardNo', title: '银行卡号', width: 200, align: 'center', templet: function (d) {
                if (d.bankCardNo == '无') {
                    return '无';
                } else {
                    return d.bankCardNo;
                }
            }
            },
            {field: 'createTime', title: '加入时间', width: 200, align:'center',templet:function(d){
                if(d.createTime == "无"){
                    return "无";
                }else {
                    return util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss');
                }
            }},
            {field: 'vipStartTime', title: '会员开始时间', width: 200, align:'center',templet:function(d){
                if(d.vipStartTime == "无"){
                    return "无";
                }else {
                    return util.toDateString(d.vipStartTime, 'yyyy-MM-dd HH:mm:ss');
                }
            }},
            {field: 'vipEndTime', title: '会员结束时间', width: 200, align:'center',templet:function(d){
                if(d.vipEndTime == "无"){
                    return "无";
                }else {
                    return util.toDateString(d.vipEndTime, 'yyyy-MM-dd HH:mm:ss');
                }
            }}
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        reloadTable();
    });

    function reloadTable() {
        type = $("#type").val();
        vipType = $("#vipType").val();
        vipStartTime = $("#vipStartTime").val();
        vipEndTime = $("#vipEndTime").val();
        param = $(".searchVal").val();

        table.reload("userListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                param: param,  //搜索的关键字
                type: type,
                vipType: vipType,
                vipStartTime: vipStartTime,
                vipEndTime: vipEndTime
            }
        })
    }
    //添加用户
    function addUser(edit) {
        var index = layui.layer.open({
            title: "编辑用户",
            type: 2,
            content: "userAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".id").val(edit.id);  //冗余ID
                    body.find(".type").val(edit.type);  //冗余TYPE
                    if (edit.name != '无') {
                        body.find(".name").val(edit.name);  //登录名
                    }
                    if (edit.phone != '无') {
                        body.find(".phone").val(edit.phone);  //手机号
                    }
                    if (edit.pPhone != '无') {
                        body.find(".pPhone").val(edit.pPhone);  //邀请人手机号
                    }
                    if (edit.bankName != '无') {
                        body.find(".bankName").val(edit.bankName);  //银行名称
                    }
                    if (edit.bankCardNo != '无') {
                        body.find(".bankCardNo").val(edit.bankCardNo);  //银行卡号
                    }
                    if (edit.shopName != '无') {
                        body.find(".shopName").val(edit.shopName);    //商户名称
                    }
                    if (edit.discount != '无') {
                        body.find(".discount").val(edit.discount);    //商户折扣
                    }
                    if (edit.shopAdress != '无') {
                        body.find(".shopAdress").text(edit.shopAdress);    //商户地址
                    }
                    if (edit.shopImage != '无') {
                        body.find(".shopImagePreview").attr("href","http://static.yantaibaixing.cn/"+edit.shopImage);    //商户照片
                        body.find(".shopImageInput").val(edit.shopImage);    //商户照片隐藏域
                    }else {
                        body.find(".shopImagePreview").text("该商户没有照片,请上传");    //商户照片
                    }
                    if (edit.longitude != '无') {
                        body.find(".longitude").val(edit.longitude);    //商户经度
                    }
                    if (edit.latitude != '无') {
                        body.find(".latitude").val(edit.latitude);    //商户纬度
                    }
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }

    $(".addNews_btn").click(function () {
        addUser();
    })

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            newsId = [];
        if (data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                reloadTable();
                // layer.close(index);
                // })
            })
        } else {
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(userList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'edit') { //编辑
            addUser(data);
        } else if (layEvent === 'usable') { //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此用户？",
                btnText = "已禁用";
            if (_this.text() == "已禁用") {
                usableText = "是否确定启用此用户？",
                    btnText = "已启用";
            }
            layer.confirm(usableText, {
                icon: 3,
                title: '系统提示',
                cancel: function (index) {
                    layer.close(index);
                }
            }, function (index) {
                _this.text(btnText);
                layer.close(index);
            }, function (index) {
                layer.close(index);
            });
        } else if (layEvent === 'myInvite') { //我的推荐
            var index = layui.layer.open({
                title: "【" + data.name + ":" + data.phone + "】的推荐",
                type: 2,
                content: "inviteList.html",
                success: function (layero, index) {
                    var body = layui.layer.getChildFrame('body', index);
                    body.find(".userId").val(data.id);  //冗余ID
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            })
            layui.layer.full(index);
            window.sessionStorage.setItem("index", index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(window.sessionStorage.getItem("index"));
            })
        } else if (layEvent === 'give') { //赠送会员
            layer.confirm('赠送会员给此用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    type: "PUT",
                    url: "http://mini.yantaibaixing.cn/vips/" + data.id,
                    dataType: "JSON",
                    success: function (data) {
                        if (data.success) {
                            top.layer.msg("赠送会员成功！");
                            reloadTable();
                            // layer.close(index);
                        }
                    }
                });
            });
        }else if (layEvent === 'cancle') { //取消会员
            layer.confirm('取消此用户的会员？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    type: "DELETE",
                    url: "http://mini.yantaibaixing.cn/vips/" + data.id,
                    dataType: "JSON",
                    success: function (data) {
                        if (data.success) {
                            top.layer.msg("取消会员成功！");
                            reloadTable();
                            // layer.close(index);
                        }
                    }
                });
            });
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    type: "DELETE",
                    url: "http://mini.yantaibaixing.cn/users/" + data.id,
                    dataType: "JSON",
                    success: function (data) {
                        if (data.success) {
                            top.layer.msg("删除用户成功！");
                            reloadTable();
                            // layer.close(index);
                        }
                    }
                });
            });
        }
    });
})
